<template>
  <div class="cart-container">
    <el-page-header @back="goBack" content="购物车" class="page-header" />

    <!-- 加载状态 -->
    <el-skeleton :rows="5" animated v-if="isLoading" />

    <!-- 购物车为空时显示 -->
    <el-empty description="购物车为空" v-else-if="Object.keys(cartItems).length === 0">
      <el-button type="primary" @click="goBack">去逛逛</el-button>
    </el-empty>

    <!-- 购物车有商品时显示 -->
    <div v-else class="cart-content">
      <div class="cart-items-container">
        <el-card
            shadow="hover"
            v-for="(quantity, productId) in cartItems"
            :key="productId"
            class="cart-item"
        >
          <div class="item-content">
            <div class="item-image-container">
              <el-image
                  :src="productInfo[productId]?.image_url || '/api/placeholder/60/60'"
                  fit="cover"
                  class="item-image"
              >
                <template #error>
                  <div class="image-placeholder">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
            </div>

            <div class="item-details">
              <h3 class="item-name">{{ productInfo[productId]?.name || '加载中...' }}</h3>
              <p class="item-desc">
                {{ productInfo[productId]?.description || '暂无描述' }}
              </p>

              <div class="item-footer">
                <div class="price-section">
                  <div class="unit-price">
                    单价: <span>￥{{ (productInfo[productId]?.price || 0).toFixed(2) }}</span>
                  </div>
                  <el-tag type="danger" size="large" class="total-price">
                    ￥{{ ((productInfo[productId]?.price || 0) * quantity).toFixed(2) }}
                  </el-tag>
                </div>

                <div class="quantity-section">
                  <span class="stock-info"
                        :class="{ 'low-stock': isLowStock(productId) }">
                    库存: {{ productInfo[productId]?.stock || '未知' }}
                  </span>
                  <el-input-number
                      v-model="cartItems[productId]"
                      :min="1"
                      :max="productInfo[productId]?.stock"
                      @change="updateCart"
                      size="small"
                      class="quantity-input"
                      controls-position="right"
                  />
                </div>
              </div>
            </div>

            <div class="action-buttons">
              <el-tooltip content="从购物车中移除" placement="top">
                <el-button
                    type="danger"
                    :icon="Delete"
                    circle
                    @click="removeItem(productId)"
                    class="delete-btn"
                />
              </el-tooltip>
            </div>
          </div>
        </el-card>
      </div>

      <el-divider />

      <el-card shadow="hover" class="summary-card">
        <div class="summary-content">
          <div class="order-summary">
            <el-row class="summary-row">
              <span>商品数量:</span>
              <span>{{ Object.keys(cartItems).length }} 件</span>
            </el-row>
            <el-row class="summary-row">
              <span>商品总数:</span>
              <span>{{ calculateTotalItems() }} 件</span>
            </el-row>
            <el-row class="summary-row total">
              <span>总计金额:</span>
              <span class="total-amount">
                ￥{{ calculateTotalPrice().toFixed(2) }}
              </span>
            </el-row>
            <el-button
                type="success"
                @click="Order"
                class="checkout-btn"
                :loading="isOrdering"
                :disabled="isOutOfStock"
                size="large"
            >
              下单结算
              <el-icon class="el-icon-right"><Wallet /></el-icon>
            </el-button>
            </div>
          </div>
      </el-card>
    </div>

    <el-divider />
    <div class="footer-actions">
      <router-link to="/customer/orders">
        <el-button type="primary" plain icon="Tickets" >查看我的订单</el-button>
      </router-link>
      <el-button type="info" plain @click="goBack" icon="ArrowLeft">继续购物</el-button>
    </div>
  </div>
</template>

<script>
import { defineComponent } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Delete, Wallet, Picture } from '@element-plus/icons-vue';

export default defineComponent({
  name: 'CartPage',
  components: {
    Delete,
    Wallet,
    Picture
  },
  data() {
    return {
      cartItems: {},
      products: [],
      productInfo: {},
      isLoading: true,
      isOrdering: false,
    };
  },
  computed: {
    Delete() {
      return Delete
    },
    // 只要有任一商品数量超过库存，就无法结算
    isOutOfStock() {
      return Object.entries(this.cartItems).some(
          ([pid, qty]) => qty > (this.productInfo[+pid]?.stock || 0)
      );
    },
  },
  created() {
    this.loadCart();
    this.loadProducts();
  },
  methods: {
    loadCart() {
      const cartData = sessionStorage.getItem('cart');
      this.cartItems = cartData ? JSON.parse(cartData) : {};
    },

    async loadProducts() {
      try {
        const response = await axios.get('/api/product');
        this.products = response.data;
        this.products.forEach((p) => {
          this.productInfo[p.id] = p;
        });
      } catch (error) {
        console.error('加载产品失败:', error);
        ElMessage.error('加载产品失败，请稍后重试！');
      } finally {
        this.isLoading = false;
      }
    },

    updateCart() {
      sessionStorage.setItem('cart', JSON.stringify(this.cartItems));
    },

    removeItem(productId) {
      ElMessageBox.confirm('确定要从购物车中删除此商品吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
          .then(() => {
            delete this.cartItems[productId];
            this.updateCart();
            ElMessage.success('删除成功');
          })
          .catch(() => {});
    },

    async Order() {
      if (this.isOutOfStock) {
        ElMessage.warning('有商品数量超过库存，无法下单');
        return;
      }
      this.isOrdering = true;
      try {
        await axios.post('/api/order', {
          customerID: sessionStorage.getItem('userId'),
          items: this.cartItems,
        });
        ElMessage.success('下单成功！');
        this.cartItems = {};
        this.updateCart();
      } catch (error) {
        console.error('下单失败:', error);
        ElMessage.error('下单失败，请重试');
      } finally {
        this.isOrdering = false;
      }
    },

    goBack() {
      this.$router.push('/product');
    },

    calculateTotalItems() {
      return Object.values(this.cartItems).reduce((sum, quantity) => sum + quantity, 0);
    },

    calculateTotalPrice() {
      return Object.entries(this.cartItems).reduce((total, [productId, quantity]) => {
        const price = this.productInfo[productId]?.price || 0;
        return total + (price * quantity);
      }, 0);
    },

    isLowStock(productId) {
      const stock = this.productInfo[productId]?.stock || 0;
      return stock > 0 && stock < 5;
    }
  },
});
</script>

<style scoped>
.cart-container {
  max-width: 1100px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.cart-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.cart-items-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.cart-item {
  margin-bottom: 0;
  transition: transform 0.2s;
}

.cart-item:hover {
  transform: translateY(-2px);
}

.item-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.item-image-container {
  width: 60px;
  height: 60px;
  flex-shrink: 0;
  border-radius: 4px;
  overflow: hidden;
}

.item-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
}

.item-details {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.item-name {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item-desc {
  margin: 0;
  font-size: 14px;
  color: #606266;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-height: 1.4;
}

.item-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
}

.price-section {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.unit-price {
  font-size: 12px;
  color: #909399;
}

.unit-price span {
  font-weight: 500;
}

.total-price {
  font-size: 16px;
}

.quantity-section {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
}

.stock-info {
  font-size: 12px;
  color: #606266;
}

.low-stock {
  color: #e6a23c;
  font-weight: 500;
}

.quantity-input {
  width: 110px;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 8px;
  text-align: center;
}

.summary-card {
  margin-top: 16px;
}

.summary-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.order-summary {
  flex: 1;
  min-width: 200px;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
  color: #606266;
}

.summary-row.total {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px dashed #dcdfe6;
  font-weight: 600;
  font-size: 16px;
  color: #303133;
}

.total-amount {
  color: #f56c6c;
  font-size: 20px;
}

.checkout-btn {
  min-width: 150px;
  text-align: center;
}

.footer-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 24px;
}

/* 响应式样式调整 */
@media (max-width: 768px) {
  .item-content {
    flex-direction: column;
    align-items: flex-start;
  }

  .item-image-container {
    width: 100%;
    height: 140px;
  }

  .item-footer {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
    width: 100%;
  }

  .quantity-section {
    flex-direction: row;
    justify-content: space-between;
    width: 100%;
    align-items: center;
  }

  .action-buttons {
    margin-top: 12px;
    align-self: flex-end;
  }

  .summary-content {
    flex-direction: column;
  }

  .checkout-btn {
    width: 100%;
  }
}
</style>